package com.github.easyms.common.util;

import com.alibaba.fastjson.JSONObject;
import com.github.easyms.common.constant.GlobalConstants;
import com.github.easyms.common.vo.ErrorVo;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Stream;

/**
 * http请求响应数据
 * @author Leo.Liao
 * @date 2020-04-09 22:30:52
 */
public class RequestHelper {

    /**
     * 从request中获取token[header-->cookie--> params]
     *
     * @param httpServletRequest
     * @return
     */
    public static String getAuthorization(HttpServletRequest httpServletRequest) {
        String authorization = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);
        if(StringUtils.isEmpty(authorization)){
            authorization = RequestHelper.getCookie(httpServletRequest,HttpHeaders.AUTHORIZATION);
        }
        if (StringUtils.isEmpty(authorization)) {
            authorization = httpServletRequest.getParameter(HttpHeaders.AUTHORIZATION);
        }
        return authorization;
    }

    /**
     * 获取请求客户端的语言 [cookie -> header -> params]
     * @param httpServletRequest
     * @return
     */
    public static Locale getLanguage(HttpServletRequest httpServletRequest, String defaultLang){
        String language =  RequestHelper.getCookie(httpServletRequest,HttpHeaders.ACCEPT_LANGUAGE);
        if(StringUtils.isEmpty(language) || !isSupportedLang(language)){
            language = httpServletRequest.getHeader(HttpHeaders.ACCEPT_LANGUAGE);
        }
        if(StringUtils.isEmpty(language) || !isSupportedLang(language)){
            language = defaultLang;
        }
        String[] lang = language.split("_");
        // 语言数组长度;语言和国际数组长度
        Integer langLength = 1;
        Integer langAndCountry = 2;
        if(lang.length == langLength){
            return new Locale(language);
        }
        if(lang.length == langAndCountry){
            return new Locale(lang[0],lang[1]);
        }else{
            return new Locale(defaultLang);
        }
    }

    /**
     * 检查是否是受支持的语言
     * @param language
     * @return
     */
    public static Boolean isSupportedLang(String language){
        List<String> acceptLanguages = GlobalConstants.Settings.ACCEPT_LANGUAGE;
        Stream<String> languageStream = acceptLanguages.stream().filter(languageCode -> languageCode.equals(language));
        if(languageStream == null || languageStream.count() == 0){
            return false;
        }
        return true;
    }

    /**
     * 获取域
     * @param request
     * @return
     */
    public static String getOrigin(HttpServletRequest request){
        return request.getHeader("Origin");
    }

    /**
     * 写入cookie
     *
     * @param response
     * @param name
     * @param value
     * @param timeout  超时时间（秒）
     */
    public static void setCookie(HttpServletResponse response, String name, String value, Integer timeout) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        if (timeout == null || timeout < 0) {
            // 30天
            timeout = 30 * 24 * 60 * 60;
        }
        cookie.setMaxAge(timeout);
        response.addCookie(cookie);
    }

    /**
     * 删除cookie
     *
     * @param response
     * @param name
     */
    public static void removeCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }

    /**
     * 获取cookie值
     *
     * @param request
     * @return
     */
    public static String getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        try {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        } catch (NullPointerException e) {
            return null;
        }
        return null;
    }

    /**
     * @param response
     */
    public static void response401(HttpServletResponse response, Integer code, String message) {
        response.setStatus(401);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            ErrorVo result = new ErrorVo(code, message);
            out.print(JSONObject.toJSON(result));
        } catch (Exception ioe) {

        } finally {
            out.flush();
            out.close();
        }
    }

}
